package day13;


import java.util.concurrent.*;

// 自定义线程池
public
class MyThreadPool<S> {
    //提供七大核心参数
    //1.定义核心线程数。如果是单线程池为1，
    private final int cpre_num=5;
    //2.定义最大线程数
    private final int max_num=10;
    //3.定义空闲线程存活时间
    private final long keep_alive_time=30;
    //4.定义时间单位
    private final TimeUnit time_unit=TimeUnit.SECONDS;
    //5.定义任务队列
    private final
    BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(cpre_num);
    //6.定义线程工厂
    private final
    ThreadFactory factory= Executors.defaultThreadFactory();
    //7.定义拒绝策略
    private final RejectedExecutionHandler handler=new ThreadPoolExecutor.AbortPolicy();
    //8.定义线程池对象（利用上面的七个参数）
    final ExecutorService pool;
    //9.提供构造方法
    public MyThreadPool(){
        pool=new ThreadPoolExecutor(
                cpre_num,
                max_num,
                keep_alive_time,
                time_unit,
                queue,
                factory,
                handler
        );
    }
    //再利用ThreadPoolExecutor构造方法 来创建线程池
    //再提供线程池 添加任务的方法execute()
    public boolean executor(Runnable runnable){
        try {
            pool.execute(runnable);
            return true;
        } catch (Exception e) {
            System.out.println("添加任务失败");
            return false;
        }
    }
    //提供一个execute方法的重载
    //前面定义泛型     后面使用泛型
    public <S> Future<S> execute(Callable<S> callable){
        Future<S> f=null;
        try {
            f= pool.submit(callable);
        } catch (Exception e) {
            System.out.println("添加任务失败");
        }
        return f;
    }
    //提供关闭线程池的方法
    public void shutdown(){
        pool.shutdown();
    }
}
class TestPool{
    public static
    void main(String[] args) throws ExecutionException, InterruptedException {
        //创建线程池对象
        MyThreadPool myThreadPool=new MyThreadPool<>();
        //利用线程池对象 执行任务
        for (int i=0;i<100;i++){
//            myThreadPool.executor(()->{
//                System.out.println(Thread.currentThread().getName()+"执行任务");
//            });
           Future<Long> f= myThreadPool.execute(()->{
               Thread t=Thread.currentThread();
              System.out.println(t.getName()+"执行任务");
              return t.getId();
           });
           Long result=f.get();
           System.out.println("任务返回结果为："+result);
        }
        //3.关闭线程池
        myThreadPool.shutdown();
    }
}